package com.ccx.coachsite.service;

import java.util.ArrayList;
import java.util.List;

import com.ccx.coachsite.CoachSiteMainActivity;
import com.ccx.coachsite.R;
import com.ccx.coachsite.bus.Account;
import com.ccx.coachsite.bus.AccountMgr;
import com.ccx.coachsite.bus.ExpertProvider;
import com.ccx.coachsite.bus.JSONTextUtils;
import com.ccx.coachsite.bus.NoReadMessageInfo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

public class ReceiveMessageTask extends AsyncTask<Integer, Integer, Boolean> {

	private Context context;
	private List<NoReadMessageInfo> messages;
	private int NewMessageId = 21234;

	public ReceiveMessageTask(Context context) {
		this.context = context;
	}

	@Override
	protected Boolean doInBackground(Integer... params) {
		messages = ExpertProvider.getInstance().getNoReadMessages(context);
		if (messages != null)
			return true;
		return false;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		if (result) {
			NotificationManager nManager = (NotificationManager) context
					.getSystemService(Service.NOTIFICATION_SERVICE);
			DisplayInfo info = new DisplayInfo();
			String users = "";
			for (NoReadMessageInfo message : messages) {
				String leaveUser = message.getLeaveUser();
				Account account = AccountMgr.readAccountInfo(context);
				if (message.getLeaveUserId() != account.getExpertId()) {
					String leaveMobile = message.getLeaveMobile();
					if (!JSONTextUtils.isEmpty(leaveMobile))
						leaveUser = message.getLeaveMobile();
				}
				pushLeaveUser(info, leaveUser);
				info.lastestLeaveUser = leaveUser;
				info.message = message.getLatestMessage();
				users += message.getLeaveUserId() + ",";
				info.messageCount++;
			}
			if (info.messageCount > 0) {
				sendNotification(nManager, info);
			} else {
				nManager.cancel(R.string.main_bottom_app_name + NewMessageId);
			}
			Intent broadcastIntent = new Intent();
			broadcastIntent.setAction("com.ccx.coachsite.UPDATE_NEW_MESSAGE");
			broadcastIntent.putExtra("newMessageCount", info.messageCount);
			broadcastIntent.putExtra("newMessageUser", users);
			context.sendBroadcast(broadcastIntent);
		}
	}

	private void pushLeaveUser(DisplayInfo info, String user) {
		for (String leaveUser : info.leaveUsers) {
			if (leaveUser.equals(user))
				return;
		}
		info.leaveUsers.add(user);
	}

	private void sendNotification(NotificationManager nManager, DisplayInfo info) {

		Notification notif = new Notification(R.drawable.icon,
				info.getDescription(), System.currentTimeMillis());

		Intent mIntent = new Intent();
		mIntent.setClass(context, CoachSiteMainActivity.class);
		mIntent.putExtra("noReadMessage", true);
		PendingIntent pIntent = PendingIntent.getActivity(context,
				NewMessageId, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		notif.flags = Notification.FLAG_AUTO_CANCEL;
		notif.setLatestEventInfo(context, "应用助理", info.getDescription(),
				pIntent);
		nManager.notify(R.string.main_bottom_app_name + NewMessageId, notif);
	}

	class DisplayInfo {

		public List<String> leaveUsers = new ArrayList<String>();
		public String lastestLeaveUser;
		public String message;
		public int messageCount = 0;

		public String getDescription() {
			if (leaveUsers.size() == 1 && messageCount == 1)
				return String.format("%1$s 给您发来一条消息:%2$s", lastestLeaveUser,
						message);
			if (leaveUsers.size() == 1 && messageCount > 1)
				return String.format("%1$s 给您发来了 %2$d 条消息", lastestLeaveUser,
						messageCount);

			return String.format("%1$d 个客户给您发来了 %2$d 条消息", leaveUsers.size(),
					messageCount);
		}
	}
}
